import React, { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import styles from "../css/order.module.css";
import "../css/global.css";
import { Toast, NavBar, Tabs } from "react-vant";

export default function OrderPage() {
  const navigate = useNavigate();
  const userInfo = JSON.parse(sessionStorage.getItem("user") || "");

  if (!userInfo) {
    navigate("/Index");
  }

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [activeTab, setActiveTab] = useState(0);

  useEffect(() => {
    const fetchOrders = async () => {
      try {
        const response = await axios.post("/mobile/order", { id: userInfo.id });
        setData(response.data.data);
      } catch (err) {
        setError("获取订单数据失败");
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchOrders();
  }, [userInfo.id]);

  const renderOrdersByStatus = (status) => {
    const filteredOrders = data.filter((order) => order.state === status);
    if (filteredOrders.length === 0) {
      return <div className={styles.no_orders}>暂无订单</div>;
    }
    return filteredOrders.map((order) => (
      <div key={order.id} className={styles.order_box}>
        <div className={styles.order_num}>订单编号: {order.order}</div>
        <div className={styles.order_content}>
          <div className={styles.order_pic}>
            <img
              src={"http://jingxun.kuxia.top" + order.commodity[0].image}
              alt=""
            />
          </div>
          <div className={styles.order_name}>{order.commodity[0].title}</div>
          <div className={styles.order_state}>
            {order.commodity[0].state === 1
              ? "待付款"
              : order.commodity[0].state === 2
              ? "待收货"
              : order.commodity[0].state === 3
              ? "已完成"
              : order.commodity[0].state === 4
              ? "已取消"
              : ""}
          </div>
        </div>
        <div className={styles.order_bottom}>
          <div className={styles.order_price}>
            应付：{order.commodity[0].price}
          </div>
          <div className={styles.orderStateBtn}>
            <div
              className={styles.order_cancel}
              onClick={() => cancelOrder(order.id)}
            >
              取消订单
            </div>
            <div className={styles.order_pay}>付款</div>
          </div>
        </div>
      </div>
    ));
  };

  const renderAllOrders = () => {
    if (data.length === 0) {
      return <div className={styles.no_orders}>暂无订单</div>;
    }
    return data.map((order) => (
      <div key={order.id} className={styles.order_box}>
        <div className={styles.order_num}>订单编号: {order.order}</div>
        <div className={styles.order_content}>
          <div className={styles.order_pic}>
            <img
              src={"http://jingxun.kuxia.top" + order.commodity[0].image}
              alt=""
            />
          </div>
          <div className={styles.order_name}>{order.commodity[0].title}</div>
          <div className={styles.order_state}>
            {order.commodity[0].state === 1
              ? "待付款"
              : order.commodity[0].state === 2
              ? "待收货"
              : order.commodity[0].state === 3
              ? "已完成"
              : order.commodity[0].state === 4
              ? "已取消"
              : ""}
          </div>
        </div>
        <div className={styles.order_bottom}>
          <div className={styles.order_price}>
            应付：{order.commodity[0].price}
          </div>
          <div className={styles.orderStateBtn}>
            <div
              className={styles.order_cancel}
              onClick={() => cancelOrder(order.id)}
            >
              取消订单
            </div>
            <div className={styles.order_pay}>付款</div>
          </div>
        </div>
      </div>
    ));
  };

  const cancelOrder = (orderId) => {
    axios
      .post("/mobile/order/del", { id: orderId })
      .then((res) => {
        // 取消订单后更新数据，删除已取消的订单
        setData(data.filter((order) => order.id !== orderId));
        Toast.success("订单已取消");
      })
      .catch((err) => {
        Toast.fail("取消订单失败");
        console.error(err);
      });
  };

  if (loading) return <div>加载中...</div>;
  if (error) return <div>{error}</div>;

  const tabContents = [
    { title: "全部", content: renderAllOrders() },
    { title: "待付款", content: renderOrdersByStatus(1) },
    { title: "待收货", content: renderOrdersByStatus(2) },
    { title: "已完成", content: renderOrdersByStatus(3) },
    { title: "已取消", content: renderOrdersByStatus(4) },
  ];

  return (
    <div className={styles.body}>
      <NavBar title="我的订单" onClickLeft={() => navigate(-1)} />
      <Tabs
        active={activeTab}
        onChange={setActiveTab}
        color="#e0af75"
        className={styles.tabs_active}
      >
        {tabContents.map((tab, index) => (
          <Tabs.TabPane key={index} title={tab.title}>
            {tab.content}
          </Tabs.TabPane>
        ))}
      </Tabs>
    </div>
  );
}
